#include "stdafx.h"
#include "title.h"

Title::Title(SceneView* _scene, QGraphicsObject* _source, const QPointF &_position_relative_source, const bool &visible = true, const QString &_text, const QString &_type) 
	: scene(_scene), source(_source), position_relative_source(_position_relative_source)//, text(_text)

{
	if (!_text.isEmpty()) text = _text;
	else text = getDefaultName(_type);
	setPlainText(text);
	setDefaultTextColor(Qt::white);
	setFlag(ItemIsMovable);
	setFlag(ItemIsSelectable);
	position_relative_source += QPointF(this->boundingRect().width() / 2, this->boundingRect().height() / 2 - 10);
	//setTextInteractionFlags(Qt::TextInteractionFlag::TextEditable);
	setPos(_source->pos() + position_relative_source);

	adjust(source->pos());
	scene->addItem(this);
	setVisible(visible);
}

void Title::mousePressEvent(QGraphicsSceneMouseEvent *event){
	update();
	QGraphicsItem::mousePressEvent(event);
}

void Title::mouseMoveEvent(QGraphicsSceneMouseEvent *event){
	update();
	QGraphicsItem::mouseMoveEvent(event);
}

void Title::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){

	//position_relative_source.setX(source->pos().x() - this->pos().x());
	position_relative_source = source->pos() - this->pos();

	update();
	QGraphicsItem::mouseReleaseEvent(event);
}

void Title::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event){
	source->setSelected(true);
}

void Title::setPosition(const QPointF &_pos){
	setPos(_pos);
	position_relative_source = source->pos() - this->pos();
}

void Title::adjust(const QPointF &_pos){
	setX(_pos.x() - position_relative_source.x());
	setY(_pos.y() - position_relative_source.y());
}

QString Title::getDefaultName(const QString &_type){
	QString text;
	int num = 0;
	bool is_unique_name = false;
	while (!is_unique_name){
		text = _type + QString::number(++num);
		is_unique_name = scene->isUniqueName(this->source, text);
	}	
	return text;
}

